package com.fenghuajueli.module_user.vip

import android.os.Bundle
import android.text.TextUtils
import androidx.activity.compose.setContent
import androidx.compose.animation.core.RepeatMode
import androidx.compose.animation.core.animateFloat
import androidx.compose.animation.core.infiniteRepeatable
import androidx.compose.animation.core.rememberInfiniteTransition
import androidx.compose.animation.core.tween
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.ExperimentalLayoutApi
import androidx.compose.foundation.layout.FlowRow
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.lazy.LazyRow
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.lazy.rememberLazyListState
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.text.ClickableText
import androidx.compose.foundation.verticalScroll
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberUpdatedState
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.TransformOrigin
import androidx.compose.ui.graphics.graphicsLayer
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.text.SpanStyle
import androidx.compose.ui.text.buildAnnotatedString
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.text.style.TextDecoration
import androidx.compose.ui.text.withStyle
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import coil.compose.AsyncImage
import com.alibaba.android.arouter.facade.annotation.Route
import com.fenghuajueli.libbasecoreui.constants.AppConfigInfo
import com.fenghuajueli.libbasecoreui.constants.PrivacyConstantsUtils
import com.fenghuajueli.libbasecoreui.data.entity.goods.GoodsEntity
import com.fenghuajueli.libbasecoreui.upload.UploadUtils
import com.fenghuajueli.libbasecoreui.user.UserInfoUtils
import com.fenghuajueli.module_route.UserModuleRoute
import com.fenghuajueli.module_user.R
import com.fenghuajueli.module_user.dialog.SubscribeDialog
import com.fenghuajueli.module_user.dialog.VipPayDialog
import com.fenghuajueli.module_user.network.model.template.NetworkTemplate
import com.fenghuajueli.module_user.network.result.TemplateResult
import com.fenghuajueli.module_user.network.model.template.UserComment
import com.fenghuajueli.module_user.ui.theme.color0091FF
import com.fenghuajueli.module_user.ui.theme.color333333
import com.fenghuajueli.module_user.ui.theme.color666666
import com.fenghuajueli.module_user.ui.theme.color787878
import com.fenghuajueli.module_user.ui.theme.color909090
import com.fenghuajueli.module_user.ui.theme.colorA7A7A7
import com.fenghuajueli.module_user.ui.theme.colorCECECE
import com.fenghuajueli.module_user.ui.widget.UserTopBarWidget
import com.fenghuajueli.module_user.ui.widget.noRippleClickable
import java.text.DecimalFormat

/**
 * @Author: sz_ijj
 * @Date: 2024-03-21 18:07
 **/
@Route(path = UserModuleRoute.USER_TEMPLATE_VIP_ACTIVITY)
class VipTemplateActivity : BaseVipActivity() {
    private var dialog: VipPayDialog? = null
    private var isFirstLoadDialog by mutableStateOf(true)

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent {
            val templateResult =
                viewModel.templateResult.collectAsState(initial = TemplateResult.Default())
            val goodsList = viewModel.goodsList.collectAsState()
            val currentGoods = viewModel.currentGood.collectAsState()
            val buttonState = viewModel.buttonUiState.collectAsState()

            when (val result = templateResult.value) {
                is TemplateResult.Success -> {
                    val showDialog by rememberUpdatedState(
                        newValue = result.data.template_type == 2 &&
                                goodsList.value.isNotEmpty() &&
                                !UserInfoUtils.getInstance().isVip()
                    )

                    //初始化付费弹窗
                    LaunchedEffect(showDialog) {
                        if (showDialog) {
                            val dialogGoods = goodsList.value.find { it.vip_type == 1 }
                            dialog = VipPayDialog(this@VipTemplateActivity)
                                .apply {
                                    entity = dialogGoods
                                    price = dialogGoods?.goods_price.toString()
                                    background = result.data.images.user_pic_member_specialoffers
                                    primaryColor = result.data.theme_color.theme_colors
                                    setListener {
                                        when (it) {
                                            "pay1" -> {
                                                viewModel.checkPayChannel(AppConfigInfo.PAY_CHANNEL_ZFB)
                                                toPay()
                                            }

                                            "pay2" -> {
                                                viewModel.checkPayChannel(AppConfigInfo.PAY_CHANNEL_WECHAT)
                                                toPay()
                                            }

                                            else -> Unit
                                        }
                                    }
                                }
                        }
                    }

                    Box(
                        modifier = Modifier
                            .fillMaxSize()
                    ) {
                        AsyncImage(
                            modifier = Modifier
                                .fillMaxSize(),
                            model = result.data.images.user_bg_background,
                            contentDescription = null,
                            contentScale = ContentScale.FillBounds
                        )
                        if (result.data.template_type == 1) {
                            //模板1
                            CommonTemplateScreen(
                                uiData = result.data,
                                currentGoods = currentGoods.value,
                                goodsList = goodsList.value,
                                isShowSubscribe = buttonState.value.subscribe,
                                isShowAliPay = buttonState.value.aliPay,
                                isShowWechatPay = buttonState.value.wechatPay,
                                isCheckSubscribe = buttonState.value.isCheck,
                                payChannel = buttonState.value.payChannel,
                                onPay = ::toPay,
                                onNotice = { SubscribeDialog(this@VipTemplateActivity).show() },
                                onAgreement = ::toPrivacyWeb,
                                checkSubscribe = viewModel::checkCurrentGoods,
                                checkPay = viewModel::checkPayChannel,
                                onPriceClick = viewModel::setCurrentGood,
                                onBackClick = ::onBackPressed
                            )
                        } else {
                            //模板2
                            CustomTemplateScreen(
                                uiData = result.data,
                                currentGoods = currentGoods.value,
                                goodsList = goodsList.value,
                                isShowSubscribe = buttonState.value.subscribe,
                                isShowAliPay = buttonState.value.aliPay,
                                isShowWechatPay = buttonState.value.wechatPay,
                                isCheckSubscribe = buttonState.value.isCheck,
                                payChannel = buttonState.value.payChannel,
                                onPay = ::toPay,
                                onNotice = { SubscribeDialog(this@VipTemplateActivity).show() },
                                onAgreement = ::toPrivacyWeb,
                                checkSubscribe = viewModel::checkCurrentGoods,
                                checkPay = viewModel::checkPayChannel,
                                onPriceClick = viewModel::setCurrentGood,
                                onBackClick = ::onBackPressed
                            )
                        }
                    }
                }

                else -> Unit
            }
        }
    }

    override fun initUpload() {
        viewModel.currentGood.value?.let {
            UploadUtils.payAction(this@VipTemplateActivity, application, it.goods_price)
        }
    }

    @Deprecated("Deprecated in Java")
    override fun onBackPressed() {
        if (dialog != null && isFirstLoadDialog) {
            dialog?.run {
                viewModel.setCurrentGood(entity)
                show()
                isFirstLoadDialog = false
            }
        } else {
            super.onBackPressed()
        }
    }
}

@Composable
internal fun CommonTemplateScreen(
    uiData: NetworkTemplate,
    currentGoods: GoodsEntity?,
    goodsList: List<GoodsEntity>,
    isShowSubscribe: Boolean,
    isShowAliPay: Boolean,
    isShowWechatPay: Boolean,
    isCheckSubscribe: Boolean,
    payChannel: String,
    onPay: () -> Unit,
    onNotice: () -> Unit,
    onAgreement: (PrivacyConstantsUtils.ProtocolType) -> Unit,
    checkSubscribe: () -> Unit,
    checkPay: (String) -> Unit,
    onPriceClick: (GoodsEntity) -> Unit,
    onBackClick: () -> Unit
) {
    Column(
        modifier = Modifier
            .fillMaxSize()
    ) {
        Box(
            modifier = Modifier
                .fillMaxWidth()
        ) {
            AsyncImage(
                modifier = Modifier
                    .fillMaxWidth(),
                model = uiData.images.user_pic_membershipcard,
                contentDescription = null,
                contentScale = ContentScale.FillWidth
            )

            UserTopBarWidget(
                primary = Color.Transparent,
                onPrimary = color333333,
                title = "会员中心",
                onBackClick = onBackClick
            )
        }

        Column(
            modifier = Modifier
                .fillMaxWidth()
                .weight(1f)
                .verticalScroll(rememberScrollState())
        ) {

            AsyncImage(
                modifier = Modifier
                    .fillMaxWidth(),
                model = uiData.images.user_pic_memberbenefits,
                contentDescription = null,
                contentScale = ContentScale.FillWidth
            )

            Row(
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(top = 3.dp, bottom = 10.dp),
                horizontalArrangement = Arrangement.SpaceEvenly
            ) {
                uiData.images.user_icon_function.forEach {
                    AsyncImage(
                        model = it,
                        contentDescription = null
                    )
                }
            }

            Text(
                modifier = Modifier
                    .padding(start = 16.dp),
                text = "会员套餐",
                color = Color.Black,
                fontSize = 16.sp,
                fontWeight = FontWeight.Bold
            )

            LazyRow(
                modifier = Modifier
                    .fillMaxWidth(),
                horizontalArrangement = Arrangement.SpaceEvenly,
                contentPadding = PaddingValues(horizontal = 6.dp)
            ) {
                items(goodsList) {
                    CommonTemplateGoodsWidget(
                        isSelect = it.id == currentGoods?.id,
                        entity = it,
                        userImgPermanentmember = uiData.images.user_img_permanentmember,
                        userImgMonthlymembership = uiData.images.user_img_monthlymembership,
                        userIconLimit = uiData.images.user_icon_limit,
                        onClick = onPriceClick
                    )
                }
            }

            SubscribeWidget(
                isShowSubscribe = isShowSubscribe,
                isCheckSubscribe = isCheckSubscribe,
                checkSubscribe = checkSubscribe,
                onNotice = onNotice,
                onAgreement = onAgreement
            )

            Text(
                modifier = Modifier
                    .padding(start = 16.dp, top = 6.dp, bottom = 16.dp),
                text = "支付方式",
                color = Color.Black,
                fontSize = 16.sp,
                fontWeight = FontWeight.Bold
            )

            if (isShowAliPay) {
                TemplateChoosePayWidget(
                    modifier = Modifier
                        .fillMaxWidth(),
                    icon = R.mipmap.user_icon_alipaypayment,
                    text = "支付宝",
                    isSelect = payChannel == AppConfigInfo.PAY_CHANNEL_ZFB,
                    onClick = {
                        checkPay(AppConfigInfo.PAY_CHANNEL_ZFB)
                    }
                )
                Spacer(modifier = Modifier.height(27.dp))
            }

            if (isShowWechatPay) {
                TemplateChoosePayWidget(
                    modifier = Modifier
                        .fillMaxWidth(),
                    icon = R.mipmap.user_icon_wechatpay,
                    text = "微信",
                    isSelect = payChannel == AppConfigInfo.PAY_CHANNEL_WECHAT,
                    onClick = {
                        checkPay(AppConfigInfo.PAY_CHANNEL_WECHAT)
                    }
                )
                Spacer(modifier = Modifier.height(27.dp))
            }
        }

        Box(
            modifier = Modifier
        ) {
            Text(
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(start = 16.dp, end = 16.dp, bottom = 29.dp)
                    .background(
                        color = uiData.theme_color.theme_colors.parseColor(),
                        shape = RoundedCornerShape(25.dp)
                    )
                    .noRippleClickable {
                        onPay()
                    }
                    .padding(vertical = 17.dp),
                text = "确认支付",
                color = Color.White,
                textAlign = TextAlign.Center,
                fontSize = 16.sp
            )
        }
    }
}

@Composable
internal fun SubscribeWidget(
    isShowSubscribe: Boolean,
    isCheckSubscribe: Boolean,
    checkSubscribe: () -> Unit,
    onNotice: () -> Unit,
    onAgreement: (PrivacyConstantsUtils.ProtocolType) -> Unit
) {
    if (isShowSubscribe)
        SubscribeTextBuilderText(
            isChecked = isCheckSubscribe,
            onChecked = checkSubscribe,
            onNotice = onNotice,
            onAgreement = onAgreement,
        )
    else
        Text(
            modifier = Modifier
                .padding(start = 16.dp, top = 6.dp, bottom = 6.dp)
                .noRippleClickable {
                    onAgreement(PrivacyConstantsUtils.ProtocolType.BUY_PROTOCOL)
                },
            text = "《会员服务协议》",
            color = color0091FF,
            fontSize = 10.sp
        )
}

@OptIn(ExperimentalLayoutApi::class)
@Composable
internal fun CustomTemplateScreen(
    uiData: NetworkTemplate,
    currentGoods: GoodsEntity?,
    goodsList: List<GoodsEntity>,
    isShowSubscribe: Boolean,
    isShowAliPay: Boolean,
    isShowWechatPay: Boolean,
    isCheckSubscribe: Boolean,
    payChannel: String,
    onPay: () -> Unit,
    onNotice: () -> Unit,
    onAgreement: (PrivacyConstantsUtils.ProtocolType) -> Unit,
    checkSubscribe: () -> Unit,
    checkPay: (String) -> Unit,
    onPriceClick: (GoodsEntity) -> Unit,
    onBackClick: () -> Unit
) {
    val state = rememberLazyListState()

//    LaunchedEffect(currentGoods) {
//        currentGoods?.let {
//            state.animateScrollToItem(goodsList.indexOf(it))
//        }
//    }

    Column(
        modifier = Modifier
            .fillMaxSize()
    ) {
        UserTopBarWidget(
            primary = Color.Transparent,
            onPrimary = color333333,
            title = "会员中心",
            onBackClick = onBackClick
        )

        Column(
            modifier = Modifier
                .fillMaxWidth()
                .weight(1f)
                .verticalScroll(rememberScrollState())
        ) {
            Spacer(modifier = Modifier.height(23.dp))

            Banner(
                data = uiData.images.user_pic_membershipcards,
            ) {
                AsyncImage(
                    modifier = Modifier
                        .fillMaxWidth(),
                    model = it,
                    contentDescription = null
                )
            }

            AsyncImage(
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(top = 16.dp, bottom = 20.dp),
                model = uiData.images.user_pic_memberbenefits,
                contentDescription = null,
                contentScale = ContentScale.FillWidth
            )

            FlowRow(
                modifier = Modifier
                    .fillMaxWidth(),
                maxItemsInEachRow = 4,
                horizontalArrangement = Arrangement.SpaceEvenly,
                verticalArrangement = Arrangement.spacedBy(8.dp)
            ) {
                uiData.images.user_icon_function.forEach {
                    AsyncImage(
                        model = it,
                        contentDescription = null
                    )
                }
            }

            AsyncImage(
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(top = 24.dp, bottom = 11.dp),
                model = uiData.images.user_pic_userreviews,
                contentDescription = null,
                contentScale = ContentScale.FillWidth
            )

            uiData.user_comments.forEach {
                CustomCommentWidget(
                    comment = it,
                    userBgEvaluation = uiData.images.user_bg_evaluation
                )
            }
        }

        Box(
            modifier = Modifier
        ) {
            AsyncImage(
                modifier = Modifier
                    .matchParentSize(),
                model = uiData.images.user_bg_price,
                contentDescription = null,
                contentScale = ContentScale.FillBounds
            )

            Column(
                modifier = Modifier
                    .padding(top = 30.dp, bottom = 20.dp)
            ) {
                LazyRow(
                    modifier = Modifier
                        .fillMaxWidth(),
                    horizontalArrangement = Arrangement.SpaceEvenly,
                    contentPadding = PaddingValues(horizontal = 6.dp),
                    state = state
                ) {
                    items(goodsList) {
                        CustomTemplateGoodsWidget(
                            isSelect = it.id == currentGoods?.id,
                            entity = it,
                            userImgPermanentmember = uiData.images.user_img_permanentmember,
                            userImgMonthlymembership = uiData.images.user_img_monthlymembership,
                            userIconLimit = uiData.images.user_icon_limit,
                            onClick = onPriceClick
                        )
                    }
                }

                SubscribeWidget(
                    isShowSubscribe = isShowSubscribe,
                    isCheckSubscribe = isCheckSubscribe,
                    checkSubscribe = checkSubscribe,
                    onNotice = onNotice,
                    onAgreement = onAgreement
                )

                val infiniteTransition = rememberInfiniteTransition(label = "infinite transition")
                val scale by infiniteTransition.animateFloat(
                    initialValue = 1f,
                    targetValue = 0.9f,
                    animationSpec = infiniteRepeatable(tween(1000), RepeatMode.Reverse),
                    label = "scale"
                )

                Text(
                    modifier = Modifier
                        .fillMaxWidth()
                        .graphicsLayer {
                            scaleX = scale
                            scaleY = scale
                            transformOrigin = TransformOrigin.Center
                        }
                        .padding(start = 16.dp, end = 16.dp, bottom = 20.dp, top = 14.dp)
                        .background(
                            color = uiData.theme_color.theme_colors.parseColor(),
                            shape = RoundedCornerShape(25.dp)
                        )
                        .noRippleClickable {
                            onPay()
                        }
                        .padding(vertical = 17.dp),
                    text = "确认支付",
                    color = Color.White,
                    textAlign = TextAlign.Center,
                    fontSize = 16.sp
                )

                Row {
                    if (isShowAliPay) {
                        TemplateChoosePayWidget(
                            modifier = Modifier
                                .weight(1f),
                            icon = R.mipmap.user_icon_alipaypayment,
                            text = "支付宝",
                            isSelect = payChannel == AppConfigInfo.PAY_CHANNEL_ZFB,
                            onClick = {
                                checkPay(AppConfigInfo.PAY_CHANNEL_ZFB)
                            }
                        )
                    }

                    if (isShowWechatPay) {
                        TemplateChoosePayWidget(
                            modifier = Modifier
                                .weight(1f),
                            icon = R.mipmap.user_icon_wechatpay,
                            text = "微信",
                            isSelect = payChannel == AppConfigInfo.PAY_CHANNEL_WECHAT,
                            onClick = {
                                checkPay(AppConfigInfo.PAY_CHANNEL_WECHAT)
                            }
                        )
                    }
                }
            }
        }
    }
}

@Composable
internal fun CustomCommentWidget(
    comment: UserComment,
    userBgEvaluation: String
) {
    Box(
        modifier = Modifier
            .padding(start = 17.dp, end = 15.dp, bottom = 10.dp)
            .fillMaxWidth()
    ) {
        AsyncImage(
            modifier = Modifier
                .matchParentSize(),
            model = userBgEvaluation,
            contentDescription = null,
            contentScale = ContentScale.FillBounds
        )

        Column {
            Row(
                modifier = Modifier
                    .padding(start = 10.dp, top = 16.dp)
            ) {
                AsyncImage(
                    modifier = Modifier
                        .size(35.dp)
                        .clip(RoundedCornerShape(50)),
                    model = comment.avatar_url,
                    contentDescription = null
                )

                Column(
                    modifier = Modifier
                        .padding(start = 12.dp)
                ) {
                    Text(
                        text = comment.user_name,
                        color = color333333,
                        fontSize = 14.sp,
                        fontWeight = FontWeight.Bold
                    )

                    Text(
                        text = "来自于 ${comment.market_type}",
                        color = color666666.copy(alpha = 0.7f),
                        fontSize = 12.sp
                    )
                }
            }

            Text(
                modifier = Modifier
                    .padding(top = 13.dp, start = 10.dp, end = 5.dp, bottom = 12.dp),
                text = comment.comment,
                color = color333333,
                fontSize = 12.sp
            )
        }
    }
}

@Composable
internal fun SubscribeTextBuilderText(
    isChecked: Boolean,
    onChecked: () -> Unit,
    onNotice: () -> Unit,
    onAgreement: (PrivacyConstantsUtils.ProtocolType) -> Unit,
    vipIntroduce: String = "会员到期自动续费：¥18  可随时取消 ",
    subscriptionNotice: String = "《订阅须知》",
    serviceAgreement: String = "《会员服务协议》",
    subscriptionAgreement: String = "《订阅协议》"
) {
    val annotatedSubscribeString = buildAnnotatedString {
        withStyle(style = SpanStyle(color = colorCECECE, fontSize = 10.sp)) {
            append(vipIntroduce)
        }

        pushStringAnnotation(
            tag = subscriptionNotice,
            annotation = subscriptionNotice
        )

        withStyle(style = SpanStyle(color = color0091FF, fontSize = 10.sp)) {
            append(subscriptionNotice)
        }

        pop()
    }

    val annotatedPrivacyString = buildAnnotatedString {
        withStyle(style = SpanStyle(color = colorCECECE, fontSize = 10.sp)) {
            append("同意")
        }

        pushStringAnnotation(
            tag = serviceAgreement,
            annotation = serviceAgreement
        )

        withStyle(style = SpanStyle(color = color0091FF, fontSize = 10.sp)) {
            append(serviceAgreement)
        }

        pop()

        withStyle(style = SpanStyle(color = colorCECECE, fontSize = 10.sp)) {
            append("和")
        }

        pushStringAnnotation(
            tag = subscriptionAgreement,
            annotation = subscriptionAgreement
        )

        withStyle(style = SpanStyle(color = color0091FF, fontSize = 10.sp)) {
            append(subscriptionAgreement)
        }

        pop()
    }

    Column(
        modifier = Modifier
            .fillMaxWidth()
    ) {

        ClickableText(
            modifier = Modifier
                .padding(start = 16.dp),
            text = annotatedSubscribeString
        ) { offset ->
            annotatedSubscribeString.getStringAnnotations(
                tag = subscriptionNotice,
                start = offset,
                end = offset
            )
                .firstOrNull()?.let {
                    onNotice()
                }
        }

        Row(
            modifier = Modifier
                .fillMaxWidth()
                .padding(start = 90.dp, top = 20.dp),
            verticalAlignment = Alignment.CenterVertically
        ) {

            AsyncImage(
                modifier = Modifier
                    .padding(end = 6.dp)
                    .size(12.dp)
                    .noRippleClickable {
                        onChecked()
                    },
                model = if (isChecked)
                    R.mipmap.user_icon_choose
                else
                    R.mipmap.user_icon_futurechoice,
                contentDescription = null
            )

            ClickableText(
                text = annotatedPrivacyString
            ) { offset ->
                annotatedPrivacyString.getStringAnnotations(
                    tag = serviceAgreement,
                    start = offset,
                    end = offset
                ).firstOrNull()?.let {
                    onAgreement(PrivacyConstantsUtils.ProtocolType.BUY_PROTOCOL)
                }

                annotatedPrivacyString.getStringAnnotations(
                    tag = subscriptionAgreement,
                    start = offset,
                    end = offset
                ).firstOrNull()?.let {
                    onAgreement(PrivacyConstantsUtils.ProtocolType.SUBSCRIBE_PROTOCOL)
                }
            }
        }
    }
}

@Composable
internal fun TemplateChoosePayWidget(
    modifier: Modifier = Modifier,
    icon: Int = R.mipmap.user_icon_alipaypayment,
    text: String = "支付宝支付",
    isSelect: Boolean,
    onClick: () -> Unit
) {
    Row(
        modifier = modifier
            .padding(horizontal = 16.dp)
            .noRippleClickable {
                onClick()
            },
        verticalAlignment = Alignment.CenterVertically
    ) {
        AsyncImage(
            modifier = Modifier
                .padding(end = 8.dp),
            model = icon,
            contentDescription = null
        )

        Text(
            text = text,
            color = color333333,
            fontSize = 14.sp
        )

        Spacer(modifier = Modifier.weight(1f))

        AsyncImage(
            modifier = Modifier
                .size(18.dp),
            model = if (isSelect) R.mipmap.user_icon_choose else R.mipmap.user_icon_futurechoice,
            contentDescription = null
        )
    }
}

@Composable
internal fun CommonTemplateGoodsWidget(
    isSelect: Boolean,
    entity: GoodsEntity,
    userImgPermanentmember: String,
    userImgMonthlymembership: String,
    userIconLimit: String,
    onClick: (GoodsEntity) -> Unit
) {
    Box(
        modifier = Modifier
            .size(120.dp, 150.dp)
            .noRippleClickable {
                onClick(entity)
            }
    ) {
        AsyncImage(
            modifier = Modifier
                .matchParentSize(),
            model = if (isSelect) userImgPermanentmember else userImgMonthlymembership,
            contentDescription = null,
            contentScale = ContentScale.FillBounds
        )

        Column(
            modifier = Modifier
                .fillMaxWidth(),
            horizontalAlignment = Alignment.CenterHorizontally
        ) {
            Text(
                modifier = Modifier
                    .padding(top = 31.dp, bottom = 10.dp),
                text = entity.goods_name,
                color = color333333,
                fontSize = 16.sp
            )

            Text(
                modifier = Modifier,
                text = "¥${entity.goods_price}",
                color = if (isSelect) Color.Black else color787878,
                fontSize = 28.sp,
                fontWeight = FontWeight.Bold
            )

            Spacer(modifier = Modifier.weight(1f))

            Text(
                modifier = Modifier
                    .padding(bottom = 18.dp),
                text = "原价：${entity.original_price}",
                textDecoration = TextDecoration.LineThrough,
                color = if (isSelect) Color.White else color909090,
                fontSize = 12.sp
            )
        }

        if (!TextUtils.isEmpty(entity.goods_badge)) {
            Box {
                AsyncImage(
                    model = userIconLimit,
                    contentDescription = null
                )

                Text(
                    modifier = Modifier
                        .align(Alignment.BottomEnd)
                        .padding(end = 10.dp, bottom = 1.dp),
                    text = entity.goods_badge,
                    color = Color.White,
                    fontSize = 12.sp,
                )
            }
        }
    }
}

@Composable
internal fun CustomTemplateGoodsWidget(
    isSelect: Boolean,
    entity: GoodsEntity,
    userImgPermanentmember: String,
    userImgMonthlymembership: String,
    userIconLimit: String,
    onClick: (GoodsEntity) -> Unit
) {
    val df = remember { DecimalFormat("#.##") }
    val price by rememberUpdatedState(newValue = df.format(
        (entity.goods_price / entity.goods_duration).let {
            if (it < 0.01) 0.01 else it
        }
    ))

    Box(
        modifier = Modifier
            .size(120.dp, 150.dp)
            .noRippleClickable {
                onClick(entity)
            }
    ) {
        AsyncImage(
            modifier = Modifier
                .matchParentSize(),
            model = if (isSelect) userImgPermanentmember else userImgMonthlymembership,
            contentDescription = null,
            contentScale = ContentScale.FillBounds
        )

        Column(
            modifier = Modifier
                .fillMaxWidth(),
            horizontalAlignment = Alignment.CenterHorizontally
        ) {
            Text(
                modifier = Modifier
                    .padding(top = 20.dp, bottom = 25.dp),
                text = entity.goods_name,
                color = if (isSelect) Color.White else color333333,
                fontSize = 16.sp
            )

            Row(
                verticalAlignment = Alignment.Bottom
            ) {
                Text(
                    modifier = Modifier
                        .padding(bottom = 2.dp),
                    text = "¥",
                    color = if (isSelect) Color.Black else colorA7A7A7,
                    fontSize = 16.sp,
                    fontWeight = FontWeight.Bold
                )

                Text(
                    modifier = Modifier,
                    text = "${entity.goods_price}",
                    color = if (isSelect) Color.Black else colorA7A7A7,
                    fontSize = 26.sp,
                    fontWeight = FontWeight.Bold
                )
            }

            Spacer(modifier = Modifier.weight(1f))

            Text(
                modifier = Modifier
                    .padding(bottom = 20.dp),
                text = "¥${if (entity.vip_type == 1) "0.01" else price}/天",
                color = if (isSelect) Color.Black else colorA7A7A7,
                fontSize = 12.sp,
            )
        }

        if (!TextUtils.isEmpty(entity.goods_badge)) {
            Box(
                modifier = Modifier
                    .align(Alignment.TopEnd)
            ) {
                AsyncImage(
                    modifier = Modifier
                        .size(58.dp, 26.dp),
                    model = userIconLimit,
                    contentDescription = null,
                    contentScale = ContentScale.FillBounds
                )

                Text(
                    modifier = Modifier
                        .align(Alignment.Center),
                    text = entity.goods_badge,
                    color = Color.White,
                    fontSize = 9.sp,
                )
            }
        }
    }
}

internal fun String.parseColor() = Color(android.graphics.Color.parseColor(this))